<template>
  <el-scrollbar height="100vh">
    <div class="container">
      <el-affix :offset="1">
        <h1 class="title">设置图层的源 setSource</h1>
      </el-affix>
      <div id="map" class="map-x" ref="mapBox"></div>
      <el-row :gutter="10" class="select">
        <el-button type="success" @click="setSource('wxMap')">设置为卫星混合图</el-button>
        <el-button type="success" @click="setSource('tfMap')">设置为碳粉图</el-button>
      </el-row>
      <dl>
        <dt>设置图层的源</dt>
        <dd>setSource()</dd>
      </dl>
      <div class="codestyle"><Code /></div>
    </div>
  </el-scrollbar>
</template>
<script>
import { toRefs, reactive, ref, onMounted } from 'vue-demi'
import Code from './code.vue'
import 'ol/ol.css'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
export default {
  setup () {
    const state = reactive({
      map: ref(null),
      mapBox: ref(null),
      layer: new Tile(),
      wxMap: new XYZ({
        url: 'https://api.maptiler.com/maps/toner/256/{z}/{x}/{y}.png?key=B3EG5uYPUvFucEWVoCa3'
      }),
      tfMap: new XYZ({
        url: 'https://api.maptiler.com/maps/hybrid/256/{z}/{x}/{y}.jpg?key=B3EG5uYPUvFucEWVoCa3'
      })
    })

    const init = () => {
      state.map = new Map({
        target: state.mapBox,
        layers: [state.layer],
        view: new View({
          // 地图视图
          projection: 'EPSG:4326', // 坐标系，有EPSG:4326和EPSG:3857
          center: [0, 0],
          zoom: 1 // 地图缩放级别（打开页面时默认级别）
        })
      })
      state.layer.setSource(state.wxMap)
    }

    // 设置图层源
    const setSource = (data) => {
      state.layer.setSource(state[data])
    }

    onMounted(() => {
      init()
    })

    return {
      init,
      setSource,
      ...toRefs(state)
    }
  },
  components: {
    Code
  }
}
</script>
<style lang="scss" scoped>
@import '../../css/main.scss';
.select {
  margin: 20px 0;
}
</style>
